﻿using EasyNetQ;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Csb.RabbitMq.Commons.Components.RabbitMq.EasyNetQ
{
    public class MQSubscribe
    {
        // MQ消息总线
        private readonly IBus bus;

        public MQSubscribe(IBus bus)
        {
            this.bus = bus;
        }

        /// <summary>
        /// 处理消息的总入口
        /// </summary>
        /// <returns></returns>
        public Task Init()
        {
            SubscribeTSysLogVis();
            //程序不结束，等待输入
            Console.WriteLine($"已启动（处理消息） {DateTime.UtcNow}");

            return Task.CompletedTask;
        }

        private Task SubscribeTSysLogVis()
        {
            var advancedBus = bus.Advanced;
            //订阅TSysLogVis日志
            var queue = advancedBus.QueueDeclare("MQueue");

            advancedBus.Consume(queue, async (body, properties, info) =>
            {
                var message = Encoding.UTF8.GetString(body.ToArray());

                Console.WriteLine($"消息处理 {DateTime.Now} : {JsonConvert.SerializeObject(message)}");
            });

            return Task.CompletedTask;
        }
    }
}
